package com.jdls.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.jdls.tanhua.dto.RecommendUserDto;
import com.jdls.tanhua.dubbo.*;
import com.jdls.tanhua.exception.AllException;
import com.jdls.tanhua.interceptor.UserHolder;
import com.jdls.tanhua.mongo.RecommendUser;
import com.jdls.tanhua.mongo.UserLike;
import com.jdls.tanhua.mongo.Visitors;
import com.jdls.tanhua.pojo.Question;
import com.jdls.tanhua.pojo.UserInfo;
import com.jdls.tanhua.template.HuanXinTemplate;
import com.jdls.tanhua.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 嘉德罗斯
 * @date 2021/10/26
 */
@Service
public class TanHuaServer {
    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private QuestionApi questionApi;

    @DubboReference
    private UserLocationApi userLocationApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public FateValueVo find() {
        Long userId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.find(userId);
        Integer round = Math.toIntExact(Math.round(recommendUser.getScore()));
        FateValueVo fateValueVo = new FateValueVo();
        fateValueVo.setFateValue(round);
        fateValueVo.setId(Math.toIntExact(recommendUser.getUserId()));
        UserInfo userInfo = userInfoApi.find(recommendUser.getUserId());

        fateValueVo.setAge(Integer.valueOf(userInfo.getAge()));
        fateValueVo.setAvatar(userInfo.getAvatar());
        fateValueVo.setGender(userInfo.getGender());
        fateValueVo.setNickname(userInfo.getNickname());
        String[] tags = userInfo.getTags().split(",");
        fateValueVo.setTags(tags);
        return fateValueVo;
    }

    //推荐好友
    public PageResult recommendation(RecommendUserDto recommendUserDto) {
        Long userId = UserHolder.getUserId();
        PageResult result = new PageResult();
        List<RecommendUser> recommendUsers = recommendUserApi.findAll(userId);
        if(recommendUsers== null || recommendUsers.size() ==0){
            return  result;
        }
        List<Long> ids = new ArrayList<>();
        //FateValueVo fateValueVo = new FateValueVo();
        for (RecommendUser recommendUser : recommendUsers) {
            Long id = recommendUser.getUserId();
            ids.add(id);
        }
        List<FateValueVo> items = new ArrayList<>();
        List<UserInfo> userInfos = userInfoApi.findScreen(ids,recommendUserDto);
        if(userInfos == null || userInfos.size() ==0){
           return  result;
        }
        for (RecommendUser recommendUser : recommendUsers) {
            FateValueVo fateValueVo = new FateValueVo();
            fateValueVo.setFateValue(Math.toIntExact(Math.round(recommendUser.getScore())));
            for (UserInfo userInfo : userInfos) {
                if(recommendUser.getUserId() ==userInfo.getId()){
                    String[] tags = userInfo.getTags().split(",");
                    fateValueVo.setTags(tags);
                    fateValueVo.setNickname(userInfo.getNickname());
                    fateValueVo.setGender(userInfo.getGender());
                    fateValueVo.setAvatar(userInfo.getAvatar());
                    fateValueVo.setAge(Integer.valueOf(userInfo.getAge()));
                    fateValueVo.setId(Math.toIntExact(userInfo.getId()));
                    break;
                }
            }
            items.add(fateValueVo);
        }

        result.setItems(items);
        result.setPage(recommendUserDto.getPage());
        result.setPageSize(recommendUserDto.getPagesize());
        result.setCounts(items.size());
        Integer pages = items.size()%recommendUserDto.getPagesize() ==0? items.size()/recommendUserDto.getPagesize() : items.size()/recommendUserDto.getPagesize()+1;
        result.setPages(pages);
        return result;
    }

    //查询佳人信息
    public FateValueVo personalInfo(Long id) {

        Long userId = UserHolder.getUserId();
        //查询当前佳人的分数
        RecommendUser recommendUser = recommendUserApi.findOne(id,userId);
        Integer round = Math.toIntExact(Math.round(recommendUser.getScore()));

        //构造返回值
        FateValueVo fateValueVo = new FateValueVo();
        fateValueVo.setFateValue(round);
        fateValueVo.setId(Math.toIntExact(id));
        UserInfo userInfo = userInfoApi.find(id);

        fateValueVo.setAge(Integer.valueOf(userInfo.getAge()));
        fateValueVo.setAvatar(userInfo.getAvatar());
        fateValueVo.setGender(userInfo.getGender());
        fateValueVo.setNickname(userInfo.getNickname());
        String[] tags = userInfo.getTags().split(",");
        fateValueVo.setTags(tags);

        //设置我去访问对方

        String from = "首页";
        //设置日期格式
        Long time = System.currentTimeMillis();
        String format = new SimpleDateFormat("yyyy-MM-dd").format(time);
        //查询当前用户今日是否是多次访问
        Visitors visitors = visitorsApi.find(id,format,from,userId);

        if (visitors == null){
            //如果不存在则保存
            visitors = new Visitors();
            visitors.setUserId(id);
            visitors.setVisitorUserId(userId);
            visitors.setScore(Double.valueOf(round));
            visitors.setDate(time);
            visitors.setFrom(from);
            visitors.setVisitDate(format);
            visitors.setIsFind(0);

            //调用Api保存
            visitorsApi.save(visitors);
        }else {
            //如果存在就更新
            String key = "visitors"+format;
            String hashKey = id.toString();
            String value = (String) redisTemplate.opsForHash().get(key, hashKey);
            Long date = value == null ? null : Long.valueOf(value);
            //如果上一次访问时间比reids里面的小
            //那么代表这次访问不是第一次访问
            if (date!=null&&visitors.getDate()<date) {
                visitors.setIsFind(1);
            }
            visitors.setDate(time);
            visitorsApi.update(visitors);
        }


        return fateValueVo;
    }

    public String strangerQuestions(Long userId) {
        Question question = questionApi.find(userId);
        return question.getTxt();
    }

    //发送陌生人消息
    public void strangerQuestions(Map map) {
        Long userId = Long.valueOf(map.get("userId").toString());
        Long id = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.find(id);

        Map map1 = new HashMap<>();
        map1.put("userId",id);
        map1.put("huanXinId","hx"+id);
        map1.put("nickname",userInfo.getNickname());
        map1.put("strangerQuestion",strangerQuestions(userId));
        String reply = map.get("reply").toString();
        map1.put("reply",reply);


        String message = JSON.toJSONString(map1);
        //第一个参数是接收人,第二个参数是发送人的信息
        Boolean aBoolean = huanXinTemplate.sendMsg("hx" + userId, message);
        if(!aBoolean){
            throw new AllException(ErrorResult.sendErr());
        }
    }

    //查询左滑右滑
    public List<TodayBest> cards() {
        Long userId = UserHolder.getUserId();
        List<RecommendUser> users = recommendUserApi.findLike(userId,10);

        //2、判断数据是否存在，如果不存在，构造默认数据 1,2,3
        //if(CollUtil.isEmpty(users)) {
        //    users = new ArrayList<>();
        //    String[] userIdS = recommendUser.split(",");
        //    for (String userId : userIdS) {
        //        RecommendUser recommendUser = new RecommendUser();
        //        recommendUser.setUserId(Convert.toLong(userId));
        //        recommendUser.setToUserId(UserHolder.getUserId());
        //        recommendUser.setScore(RandomUtil.randomDouble(60, 90));
        //        users.add(recommendUser);
        //    }
        //}
        //3、构造VO
        List<Long> ids = CollUtil.getFieldValues(users, "userId", Long.class);
        List<UserInfo> userInfos = userInfoApi.findAll(ids);

        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            for (UserInfo userInfo : userInfos) {
                if(user.getUserId() == userInfo.getId()) {
                    TodayBest vo = TodayBest.init(userInfo, user);
                    vos.add(vo);
                }
            }

        }
        return vos;
    }

    //左滑右滑
    public void love(Long id,String type) {
        Long userId = UserHolder.getUserId();
        UserLike userLike = new UserLike();
        userLike.setCreated(System.currentTimeMillis());
        userLike.setUpdated(System.currentTimeMillis());
        if ("love".equals(type)){
            userLike.setIsLike(true);
        }else {
            userLike.setIsLike(false);
        }
        userLike.setUserId(userId);
        userLike.setLikeUserId(id);
        boolean save = userLikeApi.save(userLike);
        if (save){
            //环信添加好友
            huanXinTemplate.addContact("hx"+id,"hx"+userId);
        }
    }

    //搜附近
    public List<NearUserVo> search(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        List<Long> list = userLocationApi.search(userId,distance);
        //如果附近没有人则抛异常
        if (list==null||list.size()== 0){
            throw new AllException(ErrorResult.addressErr());
        }

        for (Long id : list) {
            if (id == userId){
                list.remove(id);
                break;
            }
        }


        //根据id集合跟性别查出基本信息
        List<UserInfo> userInfos = userInfoApi.findSex(list,gender);

        //构造Vo
        List<NearUserVo> nearUserVos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            NearUserVo init = NearUserVo.init(userInfo);
            nearUserVos.add(init);
        }
        return nearUserVos;
    }
}
